package solr;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.Collection;

public class TestApp {
    SolrClient c;

    @Before
    public void init() {
        String url = "http://192.168.184.100:8983/solr/first";
        c=new HttpSolrClient.Builder(url).build();
    }

    @After
    public void destroy() throws IOException, SolrServerException {
        c.commit();
        c.close();
    }

    @Test
    public void insert()throws Exception{
        SolrInputDocument b=new SolrInputDocument();
        b.addField("id","1");
        b.addField("name","侠客行");
        b.addField("price","12");
        c.add(b);


        b=new SolrInputDocument();
        b.addField("id","2");
        b.addField("name","西游记");
        b.addField("price","5");
        c.add(b);

        b=new SolrInputDocument();
        b.addField("id","3");
        b.addField("name","三侠五义");
        b.addField("price","22");
        c.add(b);

        b=new SolrInputDocument();
        b.addField("id","4");
        b.addField("name","三国演义");
        b.addField("price","32");
        c.add(b);
    }

    @Test
    public void delete()throws Exception{
        //c.deleteById("3");//根据id删除
        //c.deleteByQuery("name:西");//根据条件查询并删除
        c.deleteByQuery("id:*");
    }

    @Test//修改，实际上就是覆盖，并没有真正修改的api
    public void update()throws Exception{
        SolrInputDocument b=new SolrInputDocument();
        b.addField("name","飞刀问情");
        b.addField("id",1);
        c.add(b);
    }

    @Test
    public void query()throws Exception{
        //设置查询条件
        SolrQuery q=new SolrQuery();

        q.setQuery("name:三");
        //按哪个字段排序
        q.setSort("price",SolrQuery.ORDER.asc);

        //执行查询
        QueryResponse resp=c.query(q);

        //获取结果
        SolrDocumentList res=resp.getResults();
        long num=res.getNumFound();
        System.out.println("结果数："+num);
        for(int i=0;i<num;i++){
            SolrDocument d=res.get(i);
            Collection<String>col=d.getFieldNames();
            for(String k:col){
                System.out.println(k+":"+d.get(k));
            }
        }

    }
}
